#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# coding=utf-8
import cgi
import wsgiref.handlers
import urllib,urllib2
import datetime
from xml.dom import minidom
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.api import urlfetch
from google.appengine.api import mail
from base import *

class MainHandler(webapp.RequestHandler):
  def get(self):
    self.response.out.write('Hello, world')

class TwitterOld(webapp.RequestHandler):    
    def get(self):
        twee = Twetts.get_by_key_name('default')
        twitter_user=twee.twitter_user
        max_id=twee.max_id
        twitter_xml_url='https://twitter.com/statuses/user_timeline/%s.xml?max_id=%s?' %(twitter_user,max_id)
        tweets = GetXml().parse_t(twitter_xml_url)
        try:            
            key_id = tweets.getElementsByTagName('status')[-1].getElementsByTagName('id')[0].firstChild.nodeValue
            if key_id<max_id:
                sbody='<ul class="loudtwitter">'
                for item in tweets.getElementsByTagName('status'):
                    text=item.getElementsByTagName('text')[0].firstChild.nodeValue
                    created_at=item.getElementsByTagName('created_at')[0].firstChild.nodeValue
                    id=item.getElementsByTagName('id')[0].firstChild.nodeValue
                    sbody += '<li>%s <a href="https://twitter.com/%s/status/%s" class="twi_time">%s</a></li>' %(text,twitter_user,id,created_at)
                
                sbody += '</ul>'
                message = mail.EmailMessage()
                mbody = sbody.encode('utf-8')
                message.html = mbody
                message.sender = "your@gmail.com" #your app admin email
                message.to = "target@email" #replace it
                message.subject = "Tweet's backup"
                message.send()
                
            twee.max_id = key_id
            twee.save()
            
        except IndexError:
            self.response.out.write("Sorry,index error.")
        

        
        self.response.out.write("OK, please check your email later.<br/>You'll receive a mail like this:<br/>%s" %mbody)

class TwitterNew(webapp.RequestHandler):    
    def get(self):
        twee = Twetts.get_by_key_name('default')
        twitter_user=twee.twitter_user
        since_id=twee.since_id
        twitter_xml_url='https://twitter.com/statuses/user_timeline/%s.xml?since_id=%s?' %(twitter_user,since_id)
        tweets = GetXml().parse_t(twitter_xml_url)
        try:            
            key_id = tweets.getElementsByTagName('status')[0].getElementsByTagName('id')[0].firstChild.nodeValue
            if key_id>since_id:
                sbody='<ul class="loudtwitter">'
                for item in tweets.getElementsByTagName('status'):
                    text=item.getElementsByTagName('text')[0].firstChild.nodeValue
                    created_at=item.getElementsByTagName('created_at')[0].firstChild.nodeValue
                    id=item.getElementsByTagName('id')[0].firstChild.nodeValue
                    sbody += '<li>%s <a href="https://twitter.com/%s/status/%s" class="twi_time">%s</a></li>' %(text,twitter_user,id,created_at)
            
                sbody += '</ul>'
                message = mail.EmailMessage()
                mbody = sbody.encode('utf-8')
                message.html = mbody
                message.sender = "your@gmail.com" #your app admin email
                message.to = "target@email" #replace it
                message.subject = "Tweet's backup"
                message.send()
            
            twee.since_id = key_id           
            twee.save()
            
        except IndexError:
            self.response.out.write("Sorry,index error.")
        
        self.response.out.write("Please wait, it will run automatically.")


def main():
  application = webapp.WSGIApplication([('/', MainHandler),
                                        ('/old',TwitterOld),
                                        ('/new',TwitterNew)
                                       ],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
  main()
